//定义每一列显示什么字段
var databaleCol = [
     {sDefaultContent: '',aTargets: [ 0 ],"bSortable": false},
     {mData: 'cardID',aTargets: [ 1 ],"bSortable": true},
     {mData: 'name',aTargets: [ 2 ],"bSortable": true},
     {mData: 'cardType',aTargets: [ 3 ],"bSortable": true},
     {mData: 'remain',aTargets: [ 4 ],"bSortable": true},
     {mData: 'type',aTargets: [ 5 ],"bSortable": true},
     {mData: 'operator',aTargets: [ 6 ],"bSortable": true},
     {mData: 'shopName',aTargets: [ 7],"bSortable": true},
     {mData: function ( source, type, val ){
    	 var date = new Date(source.dtTime);
	     var datestr = date.format('yyyy-MM-dd hh:mm:ss');
    	 return datestr;
     },aTargets: [ 8 ],"bSortable": true},
     {sDefaultContent: '',aTargets: [ 9 ],"bSortable": false}
];
var columnDefs = [
			    { "name": "cardID",   "targets": 1 },
			    { "name": "name",  "targets": 2 },
			    { "name": "cardType", "targets": 3 },
			    { "name": "remain",  "targets": 4 },
			    { "name": "type",  "targets": 5 },
			    { "name": "operator",    "targets": 6 },
			    { "name": "shopName",    "targets": 7 },
			    { "name": "dtTime",    "targets": 8 }
			  ];

var customerDatatableRequestHandle = function(obj){
	
	obj.groupBy = {groupBy:[$("input",$("span.checked",$("#tjColRadios"))).val()],sumColumn:['cRemain']};
}

var TableAjax = function () {

    var initPickers = function () {
        //init date pickers
        $('.form_meridian_datetime').datetimepicker({
            format: "yyyy-mm-dd hh:ii:ss",
            autoclose: true,
            language:"zh-CN",
            todayBtn: true,
            pickerPosition: (Metronic.isRTL() ? "bottom-right" : "bottom-left"),
            minuteStep: 5
        });
    }
    
    var loadShopName = function(){
    	$("#selectShopName");
    	$.ajax({
    		url: ctx+"/report/getAllShopName",
    		type: "GET",
    		dataType: "json",
    		success: function(jsondata, statusText, xhr) {
    			for(var i in jsondata){
    				$("#selectShopName").html($("#selectShopName").html()+"<option value=\""+jsondata[i]+"\">"+jsondata[i]+"</option>");
    			}
    			$('.bs-select').selectpicker({
                    iconBase: 'fa',
                    tickIcon: 'fa-check'
                });
    			
    		}
    		, error: function(xhr, message, error) {
    		}
    	 });
    }
    
    var handleRecords = function () {

        var grid = new Datatable();
        
        $.extend(true, $.fn.DataTable.TableTools.classes, {
            "container": "btn-group tabletools-btn-group pull-right",
            "buttons": {
                "normal": "btn btn-sm default",
                "disabled": "btn btn-sm default disabled"
            }
        });

        grid.init({
        	
            src: $("#datatable_ajax"),
            onSuccess: function (grid) {
                // execute some code after table records loaded
            },
            onError: function (grid) {
                // execute some code on network or other general error  
            },
            loadingMessage: '加载中...',
            dataTable: {
            	
            	"language": {
                    "lengthMenu": " 每页显示  _MENU_ 条记录&nbsp;",
                    "zeroRecords": "未找到记录",
                    "sInfo": "当前显示 _START_ 到 _END_ 条，共 <b>_TOTAL_</b> 条记录",
                    "info": "显示第 _PAGE_ 页，总共 _PAGES_ 页",
                    "infoEmpty": "未找到记录",
                    "sInfoFiltered": "",
                    "sProcessing": "正在加载中...",
                    "sSearch": "搜索",
                    "oPaginate": {
        			          "sFirst":    "第一页",
        			          "sPrevious": " 上一页 ",
        			          "sNext":     " 下一页 ",
        			          "sLast":     " 末页 ",
        			          "first": "第一页",
        			          "last": "末页",
        			          "next": "下一页",
        			          "page": "第",
        			          "pageOf": "页&nbsp;|&nbsp;共",
        			          "previous": "上一页"
        			      },
                    "infoFiltered": ""
                },
            	"aoColumns": databaleCol,
            	"columnDefs":columnDefs,
            	"bServerSide" : true,
            	"bProcessing":true,
                "lengthMenu": [
                    [10, 50, 100, 300],
                    [10, 50, 100, 300] // change per page values here
                ],
                "pageLength": 10, // default record count per page
                "ajax": ctx+"/report/findRechargeRecord",
                "iCookieDuration": 1,
                "order": [
                    [6, "desc"]
                ], // set first column as a default sort by asc
                "fnDrawCallback":function(oSettings){
                	$("#datatable_ajax_filter").hide();
                	$("#exportRequestJson").val(oSettings.json.exportRequestJson);
                	$("#exportPensentRequestJson").val(oSettings.json.exportRequestJson);
                	if(oSettings.json.otherTotalInfo){
                		$("#rewordTotal").html(oSettings.json.otherTotalInfo.rewordTotal);
                		$("#remainTotal").html(oSettings.json.otherTotalInfo.remainTotal);
                		$("#persent").html(oSettings.json.otherTotalInfo.persent+"%");
                	}else{
                		$("#rewordTotal").html("##");
                		$("#remainTotal").html("##");
                		$("#persent").html("##");
                	}
                },
                "dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
                "tableTools": {
                    "sSwfPath": ctx + "/static/metronic/assets/global/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
                    "aButtons": [{
                        "sExtends": "print",
                        "sButtonText": "导出门店平均折扣信息...",
                        "fnClick": function(){
                        	$("#exportFormPensent")[0].submit();
                        }
                    },{
                        "sExtends": "print",
                        "sButtonText": "导出所有...",
                        "fnClick": function(){
                        	$("#exportForm")[0].submit();
                        }
                    }, {
                        "sExtends": "print",
                        "sButtonText": "打印...",
                        "sInfo": '   "CTR+P" 打印 "ESC" 退出',
                        "sMessage": "Generated by DataTables"
                    }]
                }
            }
        });

        // handle group actionsubmit button click
        grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
            e.preventDefault();
            var action = $(".table-group-action-input", grid.getTableWrapper());
            if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
                grid.setAjaxParam("customActionType", "group_action");
                grid.setAjaxParam("customActionName", action.val());
                grid.setAjaxParam("id", grid.getSelectedRows());
                grid.getDataTable().ajax.reload();
                grid.clearAjaxParams();
            } else if (action.val() == "") {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'Please select an action',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            } else if (grid.getSelectedRowsCount() === 0) {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'No record selected',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            }
        });
    }

    return {

        //main function to initiate the module
        init: function () {
        	
            initPickers();
            handleRecords();
            loadShopName();
        }

    };

}();